import { cn } from "common-web";
import type React from "react";
import { useEffect } from "react";
import { createPortal } from "react-dom";
import Button from "./Button";
import Panel from "./Panel";

type ModalProps = {
  children?: React.ReactNode | undefined;
  visible?: boolean | null | undefined;
  onClose?: () => void;
  width?: number;
};

export default function Modal({ children, visible, onClose, width }: ModalProps) {
  useEffect(() => {
    if (visible) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
  }, [visible]);

  return (
    <>
      {createPortal(
        <div
          className={cn(
            "fixed top-0 left-0 w-screen h-screen bg-black/50 m-0 p-0 flex justify-center items-start",
            visible || "collapse",
          )}
          style={{ zIndex: 1000 }}
        >
          <Panel title="xxx" className="bg-white top-[100px] mt-48" style={{ width: width || 560 }}>
            {children}
            <Button onClick={onClose}>Close</Button>
          </Panel>
        </div>,
        document.body,
      )}
    </>
  );
}
